import { downloadFile, getBufferWithBlob, getBlobWithBuffer, getUrlWithBlob } from '@/utils/file'
import { type Ref, ref, unref } from 'vue'
import { PDFDocument } from 'pdf-lib'
import { range } from 'lodash'

export function useMergePdf(files: Ref<RecordRaw[]>) {
  const loading = ref<boolean>(false)
  const errorTitle = ref<string>('')

  /**
   * 批量解析pdf文件
   */
  const parsePDF = async () => {
    loading.value = true
    unref(files).forEach(async (file: RecordRaw) => {
      const arrayBuffer: ArrayBuffer = await getBufferWithBlob(file.raw as Blob)
      const pdf = await PDFDocument.load(arrayBuffer)
      const pageLength = pdf.getPageCount()
      file.maxNum = pageLength
      file.endNum = pageLength
      file.pdf = pdf
    })
    loading.value = false
  }

  /**
   * 合并pdf
   */
  const mergePDF = async () => {
    // 校验合并参数是否合理
    const inValid = unref(files).some((file) => file.beginNum > file.endNum)
    // 校验有问题
    if (inValid) {
      errorTitle.value = '起始页码不能大于结束页码！'
      return
    }
    // 合并
    const mergedPdf = await PDFDocument.create()
    unref(files).forEach(async (file: RecordRaw) => {
      const copiedPages = await mergedPdf.copyPages(
        file.pdf,
        range(file.beginNum, file.endNum + 1, 1),
      )
      copiedPages.forEach((page) => {
        mergedPdf.addPage(page)
      })
    })
    const mergedFileName = `merged pdf with ${unref(files)
      .map((file) => `[${file.name}][${file.beginNum}-${file.endNum}]`)
      .join('&')}`

    mergedPdf.setTitle(`🥚 ${mergedFileName} 🍳`)
    mergedPdf.setSubject('📘 mm 📖')
    mergedPdf.setAuthor('mm')
    mergedPdf.setCreator('mm')
    mergedPdf.setProducer('mm')
    mergedPdf.setCreationDate(new Date())
    mergedPdf.setModificationDate(new Date())

    const mergedPdfBytes = await mergedPdf.save()
    const blob = getBlobWithBuffer(mergedPdfBytes, 'application/pdf')
    const url = getUrlWithBlob(blob)
    downloadFile(url, `${mergedFileName}.pdf`)
  }

  return { loading, parsePDF, mergePDF, errorTitle }
}
